package net.kazed.nextaction.context.activity;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.ListActivity;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import net.kazed.nextaction.NextActionApplication;
import net.kazed.nextaction.R;
import net.kazed.nextaction.database.ContextCache;
import net.kazed.nextaction.database.GtdContext;
import net.kazed.nextaction.database.TreeNode;

/**
 * Display list of contexts.
 */
public class ContextsActivity extends ListActivity {

    public static final String SELECTED_ITEM = "SELECTED_ITEM";

    private static final int INSERT_ID = Menu.FIRST;

    private static final String cTag = "ContextsActivity";
    private static final int NEW_ITEM = 1;
    private static final int EDIT_ITEM = 2;

    private Long itemIdToSelect = null;
    private ContextListAdapter adapter;

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.contexts);
        setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT);
    }

    @Override
    protected void onResume() {
        super.onResume();

        NextActionApplication application = (NextActionApplication) getApplication();
        ContextCache contextCache = application.getContextCache();
        TreeNode<GtdContext> rootNode = contextCache.getContextTree();
        List<GtdContext> contextList = new ArrayList<GtdContext>();
        for (TreeNode<GtdContext> node : rootNode.getChildren()) {
            contextList.add(node.getData());
        }

        adapter = new ContextListAdapter(this, R.layout.context_list_item_view, contextList);
        setListAdapter(adapter);

        if (itemIdToSelect != null) {
            Log.d(cTag, "New item id = " + itemIdToSelect);

            // see if list contains the new item
            for (int i = 0; i < adapter.getCount(); i++) {
                long currentItemId = adapter.getItemId(i);
                Log.d(cTag, "Current id=" + currentItemId + " pos=" + i);
                if (currentItemId == itemIdToSelect) {
                    Log.d(cTag, "Found new item - selecting");
                    setSelection(i);
                    break;
                }
            }
            itemIdToSelect = null;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        String menuName = getResources().getString(R.string.menu_add_context);
        MenuItem item = menu.add(0, INSERT_ID, 0, menuName).setIcon(android.R.drawable.ic_menu_add);
        item.setAlphabeticShortcut('a');
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        Uri itemUri = ContentUris.withAppendedId(GtdContext.CONTENT_URI, id);

        String action = getIntent().getAction();
        if (Intent.ACTION_PICK.equals(action) || Intent.ACTION_GET_CONTENT.equals(action)) {
            // The caller is waiting for us to return a task selected by
            // the user. They have clicked on one, so return it now.
            Bundle bundle = new Bundle();
            bundle.putString(SELECTED_ITEM, itemUri.toString());
            Intent intent = new Intent();
            intent.putExtras(bundle);
            setResult(RESULT_OK, intent);
        } else {
            // Launch activity to view/edit the currently selected item
            Intent intent = new Intent();
            Bundle bundle = new Bundle();
            bundle.putString(SELECTED_ITEM, itemUri.toString());
            intent.putExtras(bundle);
            intent.setData(itemUri);
            intent.setAction(Intent.ACTION_VIEW);
            startActivityForResult(intent, EDIT_ITEM);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case INSERT_ID:
            GtdContext newContext = new GtdContext("New context");
            ContentValues values = new ContentValues();
            newContext.toValues(values);
            Uri newContextUri = getContentResolver().insert(GtdContext.CONTENT_URI, values);
            Intent contextIntent = new Intent(Intent.ACTION_INSERT, newContextUri);
            startActivityForResult(contextIntent, NEW_ITEM);
            break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
        case NEW_ITEM:
            if (resultCode == Activity.RESULT_OK) {
                if (data != null) {
                    Uri uri = data.getData();
                    itemIdToSelect = ContentUris.parseId(uri);
                }
            }
            break;
        default:
            Log.e(cTag, "Unknown requestCode: " + requestCode);
            break;
        }
    }

    private static class ContextListAdapter extends ArrayAdapter<GtdContext> {

        @Override
        public long getItemId(int position) {
            GtdContext context = getItem(position);
            return context.getId();
        }

        public ContextListAdapter(Context context, int textViewResourceId, List<GtdContext> objects) {
            super(context, textViewResourceId, objects);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            ContextView contextView;
            if (convertView instanceof ContextView) {
                contextView = (ContextView) convertView;
            } else {
                contextView = new ContextView(parent.getContext());
            }
            GtdContext context = getItem(position);
            contextView.updateView(context);
            return contextView;
        }

    }

}